<template>
  <div class="page-edit">
    <a-form
      ref="formRef"
      layout="vertical"
      :model="formState"
      :rules="formRules"
      :labelCol="{
        style: { width: '256px', fontSize: '16px', fontWeight: 500, color: '#262626', marginBottom: '8px' }
      }"
      :colon="false"
      labelAlign="left"
    >
      <a-form-item label="第一步：设置模板名称" name="name">
        <a-input
          v-model:value.trim="formState.name"
          :maxlength="30"
          placeholder="请输入模板名称（30个字以内）"
          class="w-[460px]"
        />
      </a-form-item>
      <a-form-item label="第二步：选择模板" name="style_name" class="mt-[32px]">
        <div class="flex">
          <div
            v-for="(item, index) in templateArr"
            :key="item.id"
            class="card w-[196px] h-[242px] rounded-[4px] flex flex-col p-[8px] box-sizing justify-between mr-[32px]"
            :class="{ activeCss: activeIndex == index }"
            @click="chooseTemplate(item, index)"
          >
            <div class="w-[180px] h-[180px]">
              <img :src="baseUrl + item.style_img" class="w-[180px] h-[180px]" alt="" srcset="" />
            </div>
            <div class="text-[16px] text-[#262626] font-medium mb-[8px] flex justify-between">
              <span>{{ item.name }}</span>
              <span class="preview text-[#0083ff] text-[14px] font-normal cursor-pointer" @click="handlePreview(item)"
                >预览</span
              >
            </div>
          </div>
        </div>
      </a-form-item>
      <a-form-item label="第三步：选择演示数据源（非必选）" class="pt-[8px] mb-[12px]">
        <div>
          <div class="text-[14px] text-[#262626] font-medium">内容列表演示数据</div>
          <a-form-item class="pt-[16px]" name="video_site_id">
            <div class="flex items-center text-[14px] text-[#262626]">
              <span>影片</span>
              <a-select
                v-model:value="formState.video_site_id"
                :placeholder="siteList && siteList.length > 0 ? '请选择内容' : '数据为空，请先创建广告库'"
                class="w-[460px] ml-[30px] mr-[8px]"
                allowClear
                :getPopupContainer="(triggerNode: any) => triggerNode.parentNode"
                @change="handleChange"
              >
                <a-select-option :value="item.site_id" v-for="item in siteList" :key="item.site_id">{{
                  item.site_name
                }}</a-select-option>
              </a-select>
              <a-button type="primary" class="mr-[8px]" @click="() => $router.push('/site')">创建内容</a-button>
              <a-button type="info" @click="refreshList(1)">刷新</a-button>
            </div>
          </a-form-item>
          <a-form-item class="pt-[16px]" name="article_site_id">
            <div class="flex items-center text-[14px] text-[#262626]">
              <span>图集</span>
              <a-select
                v-model:value="formState.article_site_id"
                :placeholder="siteList && siteList.length > 0 ? '请选择内容' : '数据为空，请先创建内容'"
                class="w-[460px] ml-[30px] mr-[8px]"
                allowClear
                :getPopupContainer="(triggerNode: any) => triggerNode.parentNode"
              >
                <a-select-option :value="item.site_id" v-for="item in siteList" :key="item.site_id">{{
                  item.site_name
                }}</a-select-option>
              </a-select>
              <a-button type="primary" class="mr-[8px]" @click="() => $router.push('/site')">创建内容</a-button>
              <a-button type="info" @click="refreshList(1)">刷新</a-button>
            </div>
          </a-form-item>
          <a-form-item class="pt-[16px]" name="picture_site_id">
            <div class="flex items-center text-[14px] text-[#262626]">
              <span>文章</span>
              <a-select
                v-model:value="formState.picture_site_id"
                :placeholder="siteList && siteList.length > 0 ? '请选择内容' : '数据为空，请先创建内容'"
                class="w-[460px] ml-[30px] mr-[8px]"
                allowClear
                :getPopupContainer="(triggerNode: any) => triggerNode.parentNode"
              >
                <a-select-option :value="item.site_id" v-for="item in siteList" :key="item.site_id">{{
                  item.site_name
                }}</a-select-option>
              </a-select>
              <a-button type="primary" class="mr-[8px]" @click="() => $router.push('/site')">创建内容</a-button>
              <a-button type="info" @click="refreshList(1)">刷新</a-button>
            </div>
          </a-form-item>
        </div>
        <div>
          <div class="text-[14px] text-[#262626] font-medium">广告列表演示数据</div>
          <a-form-item class="pt-[16px]">
            <div class="flex items-center text-[14px] text-[#262626]">
              <span>广告库</span>
              <a-select
                v-model:value="formState.adv_lib_id"
                class="w-[460px] ml-[16px] mr-[8px]"
                allowClear
                :placeholder="adList && adList.length > 0 ? '请选择广告库' : '数据为空，请先创建广告库'"
              >
                <a-select-option :value="item.id" v-for="item in adList" :key="item.id"
                  >{{ item.name }}
                </a-select-option>
              </a-select>
              <a-button type="primary" class="mr-[8px]" @click="() => $router.push('/adBank')">创建广告库</a-button>
              <a-button type="info" @click="refreshList(2)">刷新</a-button>
            </div>
          </a-form-item>
        </div>
      </a-form-item>
    </a-form>
    <div class="bottom-btn">
      <a-button type="primary" class="mt-[24px]" @click="createApp">{{
        templateId ? '编辑应用' : '创建应用'
      }}</a-button>
    </div>
  </div>
</template>
<script lang="ts" setup>
import { inject, onMounted, reactive, ref } from 'vue'
import apis from '@/apis'
import { message } from 'ant-design-vue'
import router from '@/router'
import { storage } from '@/utils/storage'
const {
  advertising: { list_library },
  template: { published_create, template_get, template_get_style, published_update },
  site: { list }
} = apis
const emit = defineEmits(['update-list'])
const baseUrl: any = inject('baseUrl')
console.log('baseUrl: ', baseUrl)
interface IFormState {
  name: string | undefined
  style_name: string | undefined
  type: number | undefined
  data: string
  video_site_id: string | undefined
  article_site_id: string | undefined
  picture_site_id: string | undefined
  adv_lib_id: string | undefined
  publish_status: number | undefined
  id?: string | undefined
}
const formRef = ref()
const createVisible = ref(false)
const formState = reactive<IFormState>({
  name: undefined,
  style_name: undefined,
  type: undefined,
  data: '',
  video_site_id: undefined,
  article_site_id: undefined,
  picture_site_id: undefined,
  adv_lib_id: undefined,
  publish_status: 1
})
const activeIndex = ref()
const templateId = ref()
const siteList = ref()
const adList = ref()
const templateArr = ref()
const formRules = reactive({
  name: [{ required: true, message: '请输入模板名称' }],
  style_name: [{ required: true, message: '请选择选择模板' }]
})
const handleChange = (val: any) => {
  console.log('val: ', val, formState.video_site_id)
}
//预览
const handlePreview = (item: any) => {
  console.log('item: ', item)
  router.push({
    name: 'PreviewPage',
    query: {
      advertiser_id: formState.adv_lib_id,
      video_id: formState.video_site_id,
      image_id: formState.picture_site_id,
      article_id: formState.article_site_id
    }
  })
  storage.set('style_data', item.style_data)
}
const chooseTemplate = (item: any, index: number) => {
  formState.style_name = item.style_name
  activeIndex.value = index
  formState.data = item.style_data
  console.log('formState: ', formState)
  formRef.value.clearValidate('style_name')
}
/**
 * 根据类型刷新
 * @param type
 */
const refreshList = (type: number) => {
  if (type === 1) return getSiteList(type)
  getAdList(type)
}
// // 树形结构平铺，且仅获取有完整上下级节点的，譬如【s级，web端，资源1】
// const treeToArr = (_tree: any[], _parent: CascaderProps['options'] = []) => {
//   _tree.forEach((item) => {
//     if (!item.children) {
//       formState.content.push(_parent.concat(item.value))
//     } else {
//       treeToArr(item.children, _parent.concat(item.value))
//     }
//   })
// }
//改变事件
// const handleChange = (value: any, selectedOptions: any) => {
//   console.log('value, selectedOptions: ', value, selectedOptions)
//   formState.content = []
//   selectedOptions.forEach((item: any) => {
//     const _parent = item.map((item: any) => item.value)
//     _parent.pop()
//     treeToArr([item[item.length - 1]], _parent)
//   })
//   console.log(Array.from(new Set(formState.content)), 'formState.content')
// }
//获取广告列表
const getAdList = (type?: number) => {
  // 启用中列表
  list_library({ status: 1, id: undefined, name: undefined }).then((res: any) => {
    adList.value = res?.list ?? []
    console.log('adList.value: ', adList.value)
    if (type) return message.success('刷新成功')
  })
}
//获取源数据
const getSiteList = (type?: number) => {
  list({ site_status: 1 }).then((res: any) => {
    siteList.value = res?.sites ?? []
    if (type) return message.success('刷新成功')
  })
}
// 递归属性结构转化为扁平结构
// const findIndexArray = (data: any, indexArray: any, all: any) => {
//   let arr = Array.from(indexArray)
//   for (let i = 0, len = data.length; i < len; i++) {
//     arr.push(data[i].label)
//     let children = data[i].children
//     if (children && children.length) {
//       findIndexArray(children, arr, all)
//     } else {
//       let joinArr = arr.join('/')
//       if (!all.includes(joinArr)) {
//         all.push(joinArr)
//       }
//     }
//     arr.pop()
//   }
//   return all
// }
//创建应用/更新
const createApp = () => {
  formRef.value.validate().then(() => {
    formState.type = 1
    if (!templateId.value) {
      console.log('formState: ', formState)
      published_create(formState).then(() => {
        createVisible.value = false
        message.success('创建成功')
        emit('update-list')
        router.back()
      })
    } else {
      formState.id = templateId.value
      published_update(formState).then(() => {
        createVisible.value = false
        message.success('编辑成功')
        emit('update-list')
        router.back()
      })
    }
  })
}
//获取模板
const getTemplateDetail = () => {
  template_get({ id: templateId.value }).then((res: any) => {
    console.log('模板详情: ', res)
    if (res.template.adv_lib_id == '0') res.template.adv_lib_id = undefined
    if (res.template.article_site_id == '0') res.template.article_site_id = undefined
    if (res.template.picture_site_id == '0') res.template.picture_site_id = undefined
    if (res.template.video_site_id == '0') res.template.video_site_id = undefined
    activeIndex.value = (templateArr.value || []).findIndex((item: any) => item.style_name === res.template.style_name)
    console.log('activeIndex.value: ', activeIndex.value)
    Object.assign(formState, res.template)
  })
}
//获取样式
const getStyleLst = () => {
  template_get_style().then((res: any) => {
    console.log('模板样式: ', res.list)
    templateArr.value = res?.list ?? []
  })
}
onMounted(() => {
  getAdList()
  getSiteList()
  getStyleLst()
  templateId.value = router.currentRoute.value.query?.id as string
  console.log('templateId.value: ', templateId.value)
  if (!templateId.value) return false
  getTemplateDetail()
})
</script>

<style lang="less" scoped>
:deep(.ant-form-item-no-colon) {
  font-size: 16px;
}
.page-edit {
  width: 100%;
  padding: 32px 0;
  .card {
    border: 1px solid #e8e8e8;
    background-color: #fdfefe;
    .preview {
      display: none;
    }
  }
  .bottom-btn {
    width: 100%;
    border-top: 1px solid #e8e8e8;
  }
  .card:hover {
    border: 1px solid #0083ff;
    background-color: #e4f2ff;
    box-shadow: 12px 8px 44px -12px rgba(27, 58, 146, 0.26);
  }
  .card:hover .preview {
    display: block;
  }
  .activeCss {
    border: 1px solid #0083ff;
    background-color: #e4f2ff;
    box-shadow: 12px 8px 44px -12px rgba(27, 58, 146, 0.26);
  }
}
</style>
